package com.sso.action;


import java.util.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sso.manager.SysUserManager;
import com.sso.shiro.RealmManager;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.sso.common.enums.FlagStatus;
import com.sso.common.enums.SysMenuEnum;
import com.sso.entity.vo.SysMenuVo;
import com.sso.manager.SysMenuManager;

@Controller
@RequestMapping("/")
public class LoginAction extends BaseAction{
	@Autowired
	private SysMenuManager menuManager;
	@Autowired
	private SysUserManager userManager;
	
	@RequestMapping("gotoLoginView")
	public ModelAndView loginView(){
		ModelAndView view = new ModelAndView("login");
		return view;
	}

	@RequestMapping("login")
	public ModelAndView login(String username,String password,HttpServletRequest request,HttpServletResponse response){
		ModelAndView view = new ModelAndView("");
		if(username==null && password==null){
			return view;
		}
		String flag = userManager.login(username,password);
		if(FlagStatus.ERROR.value.equals(flag)){
			view.addObject("errmsg",flag);
			view.setViewName("login");
		}else{
			view.setViewName("redirect:/index");
		}
		return view;
	}

	@RequestMapping("exit")
	public ModelAndView exit(HttpServletRequest request,HttpServletResponse response){
		Subject user = SecurityUtils.getSubject();
		user.logout();
		ModelAndView view = new ModelAndView("/login");
		return view;
	}
	@RequestMapping("index")
	public ModelAndView index(HttpServletRequest request,HttpServletResponse response){
		ModelAndView view = new ModelAndView("index");
		try{
			Map<String,Object> filterMap = new HashMap<String, Object>();
			filterMap.put("levelNum", SysMenuEnum.levelNumEnum.FIRST.value);
			List<SysMenuVo> firstMenu = menuManager.selectVoByProperty(filterMap);
			for(int i=0;i<firstMenu.size();i++){
				filterMap.put("levelNum", SysMenuEnum.levelNumEnum.SEOND.value);
				filterMap.put("parentMenuId", firstMenu.get(i).getId());
				List<SysMenuVo> second = menuManager.selectVoByProperty(filterMap);
				firstMenu.get(i).setSecondMenu(second);
			}
			Session session =SecurityUtils.getSubject().getSession();
			session.setAttribute("userMenu", firstMenu);
			view.addObject("menuList", firstMenu);
			view.addObject("sessionId", request.getSession().getId());
		}catch(Exception e){
			e.printStackTrace();
		}
		return view;
	}

}
